<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/21
 * Time: 19:52
 */

namespace app\api\job;
use app\common\model\Weekbao;
use app\common\model\WeekbaoProfit;
use app\common\model\WeekbaoSchedule;
use app\common\model\Weekbaotowallet;
use think\queue\Job;
use app\api\Service\WalletService;
use think\Db;

class HandleWallet
{
    protected $maxTime = 3;
    protected $status = 1;//已结算

    public function fire(Job $job,$data)
    {
        if( $this->handlewallet($data) ){
            echo '执行成功';
            $job->delete();
        }else{
            echo '执行失败';
            if( $job->attempts() > 3 ){ //重试3次以上删掉任务
                $job->delete();
            }
        }
        unset($data);

    }

    /**
     * 1:结算收益(InvestmentProfit)，2:更改投资(Investment)，3:记录钱包
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function handlewallet($data)
    {
        $walletService = new WalletService();
        $weekbaoSchedule = new WeekbaoSchedule();
        $weekbaotowallet = new Weekbaotowallet();
        $now =time();
        Db::startTrans();
        try{
            //结算收益
            if( isset($data['scheduleupdates']) && !empty($data['scheduleupdates']) ){
                $weekbaoSchedule->isUpdate(true)->save($data['scheduleupdates']);
            }
            if( isset($data['walletprincipal']) && !empty($data['walletprincipal']) ){ //当前时间>结束时间，返还本金和佣金且不再生成新的待结算收益

                $walletService->saveWallet(
                    $data['walletprincipal']['money'],
                    $data['walletprincipal']['user_id'],
                    $data['walletprincipal']['type'],
                    $data['walletprincipal']['remark'],
                    $data['walletprincipal']['pay_status']
                );
            }
            if( isset($data['walletprofit']) && !empty($data['walletprofit']) ){
                $walletService->saveWallet(
                    $data['walletprofit']['money'],
                    $data['walletprofit']['user_id'],
                    $data['walletprofit']['type'],
                    $data['walletprofit']['remark'],
                    $data['walletprofit']['pay_status']
                );
            }
            if( isset($data['yubaoprofit']) && !empty($data['yubaoprofit']) ){
                WeekbaoProfit::insert([
                    'schedule_id'   => $data['yubaoprofit']['schedule_id'],
                    'principal'     => $data['yubaoprofit']['principal'],
                    'day'           => $data['yubaoprofit']['day'],
                    'interest'      => $data['yubaoprofit']['interest'],
                    'status'        => $data['yubaoprofit']['status'],
                    'checkoutime'   => $data['yubaoprofit']['checkoutime']
                ]);
            }

            if( isset($data['weekbaodown']) && !empty($data['weekbaodown']) ){ //到期返还本金，下周期宝分
                Weekbao::where('user_id',$data['user_id'])->update([
                    'money' => Db::raw('money-'.$data['weekbaodown']['money']),
                ]);
                $weekbaotowallet::insert([
                    'user_id'       => $data['user_id'],
                    'change_money'  => $data['walletprincipal']['money'],
                    'from'          => 2,
                    'to'            => 1,
                    'createtime'    => $now,
                    'weekbao'       => Weekbao::where('user_id',$data['user_id'])->value('money'),
                ]);
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            file_put_contents(
                WEEKBA0_ERROR_PATH,
                '【' . date( 'Y-m-d H:i:s', $_SERVER[ 'REQUEST_TIME' ] ) . '】  用户{'.$data['user_id'].'}周期宝error:'.json_encode($e->getMessage()). PHP_EOL,
                FILE_APPEND
            );
            Db::rollback();
            return false;
        }
    }
}